package com.bingyuan.aipassproject.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.view.View;

import androidx.core.content.FileProvider;

import com.bingyuan.aipassproject.MainActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;

public class DownLoadUtils {

    public static void downLoadApk(Context context, String url,String mVersion_name){
        final String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download";
        final String fileName = "myApk.apk";
        File file = new File(filePath + "/" + fileName);
        if (file.exists())
            file.delete();
        OkGo.<File>get(url).execute(new FileCallback(filePath, fileName) {

            @Override
            public void onSuccess(Response<File> response) {

            }

            @Override
            public void onFinish() {
                super.onFinish();
                installAPK(context,filePath,fileName);
            }
        });
    }


    /*
     * 下载到本地后执行安装
     */
    public static void installAPK(Context context, String mSavePath, String fileName) {
        File apkFile = new File(mSavePath, fileName);
        if (!apkFile.exists()){
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
//      安装完成后，启动app（源码中少了这句话）
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.parse("file://" + apkFile.toString());
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
